package com.multimedia.room;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.ethernet.EthernetDevInfo;
import android.net.ethernet.EthernetManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.UserHandle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.mmclass.libsiren.EventHandler;
import com.mmclass.libsiren.LibSiren;
import com.mmclass.libsiren.LibSirenException;
import com.mmclass.libsiren.WeakHandler;
import com.multimedia.room.fragment.AllCallsFragment;
import com.multimedia.room.fragment.ExamOralDiscussFragment;
import com.multimedia.room.fragment.ExamOralFragment;
import com.multimedia.room.fragment.ExamReadyFragment;
import com.multimedia.room.fragment.ExamStandardFragment;
import com.multimedia.room.fragment.GroupDiscussFragment;
import com.multimedia.room.fragment.HeadBarView;
import com.multimedia.room.fragment.SelfRecordFragment;
import com.multimedia.room.fragment.SelfStudyFragment;
import com.multimedia.room.fragment.TeachBroadcastFragment;
import com.multimedia.room.fragment.TeachDemonstrationFragment;
import com.multimedia.room.fragment.TeachDictationFragment;
import com.multimedia.room.fragment.TeachIntercomFragment;
import com.multimedia.room.fragment.TeachMonitorFragment;
import com.multimedia.room.fragment.TeachTestFragment;
import com.multimedia.room.fragment.TeachTranslateFragment;
import com.multimedia.room.fragment.WelcomeFragment;
import com.multimedia.room.upgrade.Constants;
import com.multimedia.room.upgrade.DownloadTask;
import com.multimedia.room.upgrade.IDownloadListener;
import com.multimedia.room.upgrade.RebootTask;
import com.multimedia.room.upgrade.Session;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;


public class BaseActivity extends Activity {
    protected static final String PKG = "com.multimedia.room";
    private static final String TAG = "BaseActivity";
    private static LibSiren mLibSiren;
    protected static EventHandler em = EventHandler.getInstance();
    protected static Context mBaseContext;
    protected static String mSeatNo;
    private static CommonUtil mUtil;
    static String seatPrefix;
    static String seatSuffix;
    RelativeLayout mBaseView;
    TextView mBottomView;
    private static String mGroupAddr;
    private LinearLayout mRocketView;

    private static boolean mIsInitialized;
    protected static String mCurrentMOde;

    private static SwitchManager mSwitchManager;
    private static HeadBarView mHeadBarView;

    private boolean mIsInternetConnected = false;
    private ConnectivityManager mConnectivityManager;
    private final NetworkReceiver mNetworkReceiver = new NetworkReceiver();
    private static boolean mNetworkReceiverRegistered = false;

    protected static Object sObjectLock = new Object();
    private MessageHandler mHandler;
    private long mOldTime, mNewTime;

    private static boolean sIsDownloaded = false;
    private DownloadTask mDownloadTask;

    private Handler mDownloadHandler;
    private ProgressDialog m_pDialog;
    private static boolean mIsConnected = false;
    private static Object mLock = new Object();
    private static final String UPGRADE_ACTION_STRING = "com.multiroom.action.UPGRADE";
    private PowerManager mPowerManager;
    private Session mSession;
    private HandlerThread mThread = new HandlerThread("SystemUpgrade");
    private static final String CACHE_FILE = "/cache/update/update.zip";

    private static final String MESSAGE_ACTION = "com.multimedia.room.action.GET_MESSAGE";
    private static final String ALARM_ACTION = "com.multimedia.room.action.ALARM_MESSAGE";
    private static final String MESSAGE_CONTENT = "data";
    private static boolean sIsSpeakerStatus = false;
    private static final int TIME_FIVE_MINUTES = 1*60 * 1000;
    private static final int TIME_TWO_MINUTES = 2*60 * 1000;
    private static final int TIME_THREE_MINUTES = 3*60 * 1000;
    private static final int TIME_ONE_MINUTES = 1*60 * 1000;
   private static final int PING_PERIOD = 10*60*1000;
   private static AlertDialog sAlertDialog;
   private static String sCheckUrl = "http://192.168.1.11:8080/API/GetStatus?id=";
   private static boolean sIsAlive = false;

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "action for msg " + intent.toString());
            // for test without teacher clieat
            // am broadcast -a com.multimedia.room.action.GET_MESSAGE --es data
            // "{"type":"cmd","receiver":"all","mode":"global","command":"setting","group":"null","param":"on"}"

//            String command = "\"{\"type\":\"cmd\",\"receiver\":\"all\",\"mode\":\"global\",\"command\":\"clean_cache\",\"group\":\"null\",\"param\":\"on\"}\"";
            if (intent.getAction().equals(MESSAGE_ACTION)) {
                String data = intent.getStringExtra(MESSAGE_CONTENT);
                Log.d("message", data);
                handleCustomMessage(BaseActivity.this, data);
            } else if(intent.getAction().equals(ALARM_ACTION)){
                Log.i(TAG,"ALARM_ACTION");
//                CommandManager.sendSetOnlineMessage();
                sIsAlive = false;
                checkTeachServer();

            }
            else {
                Log.d(TAG, "no action for msg " + intent.getAction());
            }

        }
    };

    private class MessageHandler extends Handler {
        public static final int UPDATE_NET_STATUS = 1101;
        public static final int SIREN_INIT_FINISH_STATUS = 1102;
        public static final int UPDAGE_DOWNLOADING = 1103;
        public static final int MSG_KILL_PROCESS = 1104;
        public static final int PING_ERROR=1105;
        public static final int PING_SUCCESS=1106 ;
        public static final int CHECK_ALIVE=1107;
        public static final int CHECK_HEADSTATUS=1108;
        public static final int REBOOT = 1109;
        MessageHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATE_NET_STATUS:
                    Log.d(TAG, "UPDATE_NET_STATUS " + "mIsInitialized " + mIsInitialized);
                    if (checkNetworkAvailable() && !mIsInitialized) {
                        Log.d(TAG, "UPDATE_NET_STATUS " + "mIsInitialized " + mIsInitialized);
                        if (mLibSiren != null) {
                            mLibSiren.destroy();
                        }
                        synchronized (sObjectLock) {
                            new Thread(new Runnable() {

                                @Override
                                public void run() {
                                    mHandler.postDelayed(preInvokeNativeTask, 300);
                                }
                            }).start();
                        }

                    } else if (!mIsInternetConnected) {
                        Log.d(TAG, "UPDATE_NET_STATUS " + "mIsInternetConnected " + mIsInternetConnected);
                        Log.d(TAG, "network disconnect  " + "destory sat!");
                        if (mLibSiren != null) {
                            mLibSiren.destroy();
                            mIsInitialized = false;
                        }
                        loadErrorNetworkFragment();
                        return;
                    }
                    break;
                case SIREN_INIT_FINISH_STATUS:
                    Log.d(TAG, "SIREN_INIT_FINISH_STATUS");
                    loadFirstFragment();
                    break;
                case UPDAGE_DOWNLOADING:
                    m_pDialog.setMax((int) msg.arg2);
                    m_pDialog.setProgress((int) msg.arg1);
                    if (msg.arg1 >= msg.arg2) {
                        //download finish
                        m_pDialog.dismiss();
                    }
                    break;
                case MSG_KILL_PROCESS:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            killOtherProcess();
                        }
                    }).start();
                    break;
                case PING_ERROR:
                    //showDialog();
                    mHeadBarView.setOnline(false);
                    break;
                case PING_SUCCESS:

                   break;
                case CHECK_ALIVE:
                    Log.i(TAG,"CHECK_ALIVE"+sIsAlive);
                    if(sIsAlive){
                        mHeadBarView.setOnline(true);
                        //ping通 命令通
                       // dimissDialog();
                    }else{
                        mHeadBarView.setOnline(false);
                      //  showDialog();
                    }

                case CHECK_HEADSTATUS:
                    Log.i(TAG,"CHECK_HEADSTATUS");
                    int flag = CommandManager.getHeadSetStatus();

                    //0 open
                    // 1 close
                    if(flag == 1 && sTryTimes<= MAX_TIMES){
                        Log.i(TAG," CHECK_HEADSTATUS head set is close open it");
                        CommandManager.openHeadSet();
                        sTryTimes ++;
                        mHandler.sendEmptyMessageDelayed(CHECK_HEADSTATUS,5*1000);
                    }else if(flag ==1){
                        //Reboot
                        Log.i(TAG," CHECK_HEADSTATUS head set ignore, has try open it 10 times ");
//                        showRebootDialog();
                    }
                    break;
                case REBOOT:
                    if(mIsNeedAutoReboot){
                        PowerManager pManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
                        pManager.reboot("reboot");
                    }
                    break;
                default:
                    break;
            }
        }
    }
    private static int sTryTimes = 0;
    private static final int MAX_TIMES = 10;
    final Runnable preInvokeNativeTask = new Runnable() {
        public void run() {
            preInvokeNativeMethod();
        }
    };
    // clean listener
    private static ArrayList<ICleanListener> mCleanerList = new ArrayList<ICleanListener>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBaseContext = getApplicationContext();
        setContentView(R.layout.base_activity_layout);
        CommonUtil.getInstance(getApplicationContext());
        mBaseView = (RelativeLayout) findViewById(R.id.base_layout);
        mBottomView = (TextView)findViewById(R.id.bottom_view);
        mHeadBarView = (HeadBarView) findViewById(R.id.title_layout);
        changeBg();
        /* first, we must get the Service. */
        mHandler = new MessageHandler(Looper.getMainLooper());
        mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

        m_pDialog = new ProgressDialog(getApplicationContext());

        m_pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        m_pDialog.setTitle("系統升级");
        m_pDialog.setMessage("发现升级文件，正在下载，请不要关机");
        m_pDialog.setCancelable(false);
        m_pDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        registerNetworkReceiver();
        loadWelcomeFragment();
        init();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MESSAGE_ACTION);
        filter.addAction(ALARM_ACTION);
        registerReceiver(mBroadcastReceiver, filter);
    }

    private void changeBg(){
        if(CommonUtil.APP_THEME_DEFAULT.equals(CommonUtil.getTheme())){
            mBaseView.setBackgroundResource(R.drawable.bg1);
            mBottomView.setVisibility(View.GONE);
            mHeadBarView.setMarkStatus(false);
        }else if(CommonUtil.APP_THEME_1.equals(CommonUtil.getTheme())){
            mBaseView.setBackgroundResource(R.drawable.bg2);
            mBottomView.setVisibility(View.VISIBLE);
            mHeadBarView.setMarkStatus(true);
        }else if(CommonUtil.APP_THEME_2.equals(CommonUtil.getTheme())){
            mBaseView.setBackgroundResource(R.drawable.bg3);
            mBottomView.setVisibility(View.VISIBLE);
            mHeadBarView.setMarkStatus(true);
        }else if(CommonUtil.APP_THEME_3.equals(CommonUtil.getTheme())){
            mBaseView.setBackgroundResource(R.drawable.bg4);
            mBottomView.setVisibility(View.VISIBLE);
            mHeadBarView.setMarkStatus(true);
        }
    }


    @Override
    protected void onStart() {
        super.onStart();



    }

    private void setAlarm(){
        Random ran1 = new Random(10);
        int pingPeriod = ran1.nextInt() *PING_PERIOD ;
        Log.i(TAG,"setAlarm pingPeriod: "+pingPeriod);
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);//获取AlarmManager实例
        int anHour =  6 * 1000 ;  // 6秒
        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
        Intent intent2 = new Intent(ALARM_ACTION);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent2, 0);
        manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, TIME_ONE_MINUTES, PING_PERIOD, pi);//开启提醒
    }



    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            try {
//                checkNetWork("192.168.1.11");
                checkTeachServer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private void checkNetWork(String addr){
        String cmd = "ping -c 10 -w 10 " + addr;
        Log.d("checkNetWork", "cmd "+cmd);
        ShellUtils.CommandResult commandResult = ShellUtils.execCommand(cmd, false);
        Log.i("checkNetWork", commandResult.toString());
        if(commandResult.successMsg.contains("100% packet loss")){
            Log.i("checkNetwork" ,"与 " + addr + " 连接不畅通."+commandResult);
            mHandler.removeMessages(MessageHandler.PING_ERROR);
            mHandler.sendEmptyMessage(MessageHandler.PING_ERROR);
        }else{
            mHandler.removeMessages(MessageHandler.PING_SUCCESS);
            mHandler.sendEmptyMessage(MessageHandler.PING_SUCCESS);
            Log.i("checkNetwork" ,"与 " + addr + " 连接畅通."+commandResult);
        }
    }

    private void init() {
        initDownload();
        mSwitchManager = SwitchManager.getInstance();
        mBaseContext = BaseActivity.this;
        mUtil = CommonUtil.getInstance(mBaseContext);
        mConnectivityManager = (ConnectivityManager) mBaseContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        // CommonUtil.reStoreValueIntoSharePreferences(CommonUtil.SEATNO, "A1");
        mSeatNo = CommonUtil.getSeatNo();
        CommandManager.SetSeatNo(mSeatNo);
        mHeadBarView.setTitle(mSeatNo);
        mHeadBarView.setOnline(true);
        if (!CommonUtil.isConfigIP()||CommonUtil.getGateWay()!=11) {
            handle_saveconf(CommonUtil.getIpPrefix());
            if (mHandler != null) {
                mHandler.removeMessages(MessageHandler.UPDATE_NET_STATUS);
                mHandler.sendEmptyMessageDelayed(
                        MessageHandler.UPDATE_NET_STATUS, 2000);
            }
            CommonUtil.configIP(true);
            CommonUtil.configGATEWAY(11);
        } else {
            if (checkNetworkAvailable()) {
                mHandler.removeMessages(MessageHandler.UPDATE_NET_STATUS);
                mHandler.sendEmptyMessageDelayed(
                        MessageHandler.UPDATE_NET_STATUS, 2000);
            }
        }
        sendBroadcastAsUser(new Intent(UPGRADE_ACTION_STRING), UserHandle.CURRENT);
       /* try{
        Intent intent = new Intent();
                                intent.setClassName("com.exosft.studentclient",
                                                "com.exosft.studentclient.activity.UIHomeActivity");
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
        }catch(Exception e){}
      */
    }

    private void preInvokeNativeMethod() {
        if (mIsInitialized) {
            Log.d(TAG, "LibSiren has initialisation");
            return;
        }
        if (!checkNetworkAvailable()) {
            Log.d(TAG, "network is unavailable");
            mIsInitialized = false;
            return;
        }

        LibSiren.updateAddress();
        Log.d(TAG, "LibSiren initialisation");
        try {

            mLibSiren = LibSiren.getInstance();

        } catch (LibSirenException e) {
            Log.d(TAG, "LibSiren initialisation failed");
            return;
        }
        try {
            // ToDo:return value
            mLibSiren.init(getBaseContext());
            try {
                Thread.sleep(1000);

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (mLibSiren == null) {
                return;
            }
            CommandManager.SetLibSiren(mLibSiren);
            checkEth0DeviceAndSetStatus();
            CommandManager.sendSetOnlineMessage();
            HeadBarView.setInitVolume();
            //killSelfForHeadSet();
            mHandler.sendEmptyMessage(MessageHandler.SIREN_INIT_FINISH_STATUS);
            mHandler.sendEmptyMessageDelayed(MessageHandler.CHECK_HEADSTATUS,1*60*1000);
            // instance the event handler
            em.addHandler(baseEventHandler);
            mIsInitialized = true;
            setAlarm();
//            timer.schedule(task,TIME_FIVE_MINUTES,PING_PERIOD);
        } catch (LibSirenException e) {
            // TODO Auto-generated catch block
            mIsInitialized = false;
            e.printStackTrace();
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG,"onStop");

    }


    /**
     * Handle libsiren asynchronous events
     */
    private Handler baseEventHandler = new BaseJNIEventHandler(this);

    private class BaseJNIEventHandler extends WeakHandler<BaseActivity> {
        public BaseJNIEventHandler(BaseActivity owner) {
            super(owner);
        }

        @Override
        public void handleMessage(Message msg) {
            BaseActivity activity = getOwner();
            if (activity == null)
                return;
            String data = msg.getData().getString("data");
            handleCustomMessage(activity, data);
        }

        ;
    }

    private void handleCustomMessage(Activity activity, String data) {
        // Do not handle events if we are leaving the TestJniActivity
        // ToDo:

        if (data.contains("VOICE-DB")) {
            if (mVolumeChangeListener != null) {
                try {
                    JSONObject jsonStr = new JSONObject(data);
                    String value = jsonStr.getString("VOICE-DB");
                    mVolumeChangeListener.volumeChanger(value);
                } catch (Exception e) {
                    Log.e(TAG, "parse the voice value error ", e);
                }
            }
//            Log.d(TAG, "record volume change return");
            return;
        }
        final MediaMessage message = CommonUtil.parseMessage(data);
        if (message == null) {
            return;
        }
        Log.d(TAG, "message " + message.toString());
        final String params = message.getParams();
        mCurrentMOde = message.getMode();
        if (!mCurrentMOde.equals(Command.Modes.MODE_GROUP)
                && message.getReveiver().equals("teacher")) {
            Log.w(TAG,"handleCustomMessage : Receiver is teacher ignore this message");
            return;
        }
        try {

            Log.i(TAG," mCurrentMOde "+ params);
            if (mCurrentMOde.equals(Command.Modes.MODE_TEACH)) {
                Log.i(TAG," MODE_TEACH" );
                mHandler.removeMessages(MessageHandler.MSG_KILL_PROCESS);
                mHandler.sendEmptyMessage(MessageHandler.MSG_KILL_PROCESS);
                mHeadBarView.setModel(R.string.teach_model);
                loadTeachingFragment(message);
            } else if (mCurrentMOde.equals(Command.Modes.MODE_EXAM)) {
                Log.i(TAG," MODE_EXAM" );
                mHandler.removeMessages(MessageHandler.MSG_KILL_PROCESS);
                mHandler.sendEmptyMessage(MessageHandler.MSG_KILL_PROCESS);
                mHeadBarView.setModel(R.string.exam_model);
                loadExamFragment(message);
            } else if (mCurrentMOde.equals(Command.Modes.MODE_GROUP)) {
                Log.i(TAG," MODE_GROUP" );
                mHandler.removeMessages(MessageHandler.MSG_KILL_PROCESS);
                mHandler.sendEmptyMessage(MessageHandler.MSG_KILL_PROCESS);
                mHeadBarView.setModel(R.string.group_model);
                loadGroupFragment(message);
            } else if (mCurrentMOde.equals(Command.Modes.MODE_SELF_STUDY)) {
                Log.i(TAG," MODE_SELF_STUDY" );
                mHandler.removeMessages(MessageHandler.MSG_KILL_PROCESS);
                mHandler.sendEmptyMessage(MessageHandler.MSG_KILL_PROCESS);
                mHeadBarView.setModel(R.string.study_model);
                loadStudyFragment(message);
            } else if (mCurrentMOde.equals(Command.Modes.MODE_GLOBAL)) {
                Log.i(TAG," MODE_GLOBAL" );
                if (!message.getTpye().equals("cmd")) {
                    Log.w(TAG,"handleCustomMessage : message tpye isn't \"cmd\" ignore this message");
                    return;
                }
                if (message.getCommand().equals(
                        Command.COMMANDS.COMMAND_CLEAN_CACHE)) {

                    DataCleanManager.cleanApplicationData(getApplicationContext());
//                    showRocektShot();
                }
                else if (Command.COMMANDS.COMMAND_GLOBAL_SETMIC.equals(message
                        .getCommand())) {
                    Log.d(TAG," setBoostMic "+ message);
                    CommandManager.setBoostMic(Integer.parseInt(params));

                }else if (message.getCommand().equals(
                        Command.COMMANDS.COMMAND_GLOBAL_SPEAKER)) {
                    if ("on".equals(message.getParams())) {
                        Log.d(TAG, "speaker on close headset");
                        sIsSpeakerStatus = true;
                        CommandManager.closeHeadSet();
                    } else if ("off".equals(message.getParams())) {
                        Log.d(TAG, "speaker off open headset");
                        sIsSpeakerStatus = false;
                        try {
                            CommandManager.closeHeadSet();
                            Thread.sleep(3000);
                            CommandManager.openHeadSet();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                    return;
                } else if (message.getCommand().equals(
                        Command.COMMANDS.COMMAND_GROUP_BROADCAST)) {

                    if ("on".equals(message.getParams())) {

                        CommandManager.startSat();
                        CommandManager.leaveGroup("");
                        CommandManager.joinGroup("230.1.2.3");
                        CommandManager.closeMic();
                        Log.i(TAG,"join group");
                        CommandManager.sendRemoteVGAOut();
                        turnOffScreen();
                        try {
                            CommandManager.closeHeadSet();
                            Thread.sleep(3000);
                            CommandManager.openHeadSet();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    } else if ("off".equals(message.getParams())) {
                        CommandManager.sendLocalVGAOut();
                        turnOnScreen();
                    } else if ("pc".equals(message.getParams())) {
                        CommandManager.sendLocalPCOut();
                        Log.d(TAG, "pc");
                    } else if ("mobile".equals(message.getParams())) {
//                        CommandManager.sendLocalPCOut();
                        Log.d(TAG, "mobile");
                        CommandManager.startSat();
                        CommandManager.leaveGroup("");
                        CommandManager.joinGroup("230.1.2.3");
                        CommandManager.closeMic();
                        Log.i(TAG,"join group");
                        CommandManager.sendRemoteVGAOut();
                        turnOffScreen();
                        try {
                            CommandManager.closeHeadSet();
                            Thread.sleep(3000);
                            CommandManager.openHeadSet();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                    return;
                } else if (message.getCommand().equals(
                        Command.COMMANDS.COMMAND_SETTING)) {

                    Intent intent = new Intent();
                    intent.setClassName("com.android.settings",
                            "com.android.settings.Settings");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } else if (message.getCommand().equals(
                        Command.COMMANDS.COMMAND_UPGRADE)) {
                    Log.d(TAG, "upgrade " + message.getParams());
                    if (!sIsDownloaded) {
                        if (!TextUtils.isEmpty(message.getParams())) {
                            download(message.getParams());
                            Log.d(TAG, "system update!");
                        } else {
                            Log.e(TAG, "system update error ,Url is null");
                        }
                    } else {
                        Log.e(TAG, "no need upgrade!");
                    }
                } else if (message.getCommand()
                        .equals(Command.COMMANDS.COMMAND_REBOOT)) {
                    Log.d(TAG, "rebot!");
                    PowerManager pManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
                    pManager.reboot("reboot");
                } else if (message.getCommand().equals(
                        Command.COMMANDS.COMMAND_VERSION)) {
                    Log.d(TAG, "version!");
                    CommonUtil.showDialog(mBaseContext, "系统版本", "系统版本号为: "
                            + Build.DISPLAY);
                    CommonUtil.showSelectedDialog(mBaseContext);
                } else if (message.getCommand().equals(
                        Command.COMMANDS.COMMAND_RECOVERY)) {
                    RebootTask task = new RebootTask(mSession);
                    mDownloadHandler.post(task);
                }
                // TODO ...
                else if (!message.getReveiver().equals("teacher")
                        && Command.COMMANDS.COMMAND_GLOBAL_ONLINE
                        .equals(message.getCommand())) {
                    CommandManager.sendSetOnlineMessage();

                } else if (message.isMe()
                        && Command.COMMANDS.COMMAND_GLOBAL_ONLINE_OK
                        .equals(message.getCommand())) {

//                    CommandManager.sendSetOnlineMessage();

                }else if (message.isMe()
                        && Command.COMMANDS.KILL_SELF
                        .equals(message.getCommand())) {
                    //sIsAlive = true;
                    Log.i(TAG,"kill self");
                    android.os.Process.killProcess(android.os.Process.myPid());
                }


                // TODO ...
                else if (!message.getReveiver().equals("teacher")
                        && Command.COMMANDS.COMMAND_CHANGE_IP.equals(message
                        .getCommand())) {
                    CommonUtil.setIpPrefix(message.getParams());
                    handle_saveconf(message.getParams());
                    if (mHandler != null) {
                        mHandler.removeMessages(MessageHandler.UPDATE_NET_STATUS);
                        mHandler.sendEmptyMessageDelayed(
                                MessageHandler.UPDATE_NET_STATUS, 2000);


                    }
                    CommonUtil.configIP(true);
                    CommonUtil.configGATEWAY(11);
                }

                // Set seat
                else if (Command.COMMANDS.COMMAND_SET_SEAT.equals(message
                        .getCommand())) {
                    View dialogView = LayoutInflater.from(activity).inflate(
                            R.layout.dialog_seat, null);
                    Spinner prefixSpinner = (Spinner) dialogView
                            .findViewById(R.id.seat_prefix);
                    Spinner suffixSpinner = (Spinner) dialogView
                            .findViewById(R.id.seat_suffix);
                    prefixSpinner.setAdapter(new ArrayAdapter<String>(activity,
                            android.R.layout.simple_spinner_item,
                            CommonUtil.sSeatPrefix));
                    suffixSpinner.setAdapter(new ArrayAdapter<String>(activity,
                            android.R.layout.simple_spinner_item,
                            CommonUtil.sSeatsuffix));

                    prefixSpinner
                            .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                                @Override
                                public void onItemSelected(AdapterView<?> arg0,
                                                           View arg1, int arg2, long arg3) {
                                    seatPrefix = CommonUtil.sSeatPrefix[arg2];

                                }

                                @Override
                                public void onNothingSelected(
                                        AdapterView<?> arg0) {
                                    // TODO nothing to do.

                                }
                            });
                    suffixSpinner
                            .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                                @Override
                                public void onItemSelected(AdapterView<?> arg0,
                                                           View arg1, int arg2, long arg3) {
                                    seatSuffix = CommonUtil.sSeatsuffix[arg2];
                                }

                                @Override
                                public void onNothingSelected(
                                        AdapterView<?> arg0) {
                                    // TODO nothing to do.

                                }
                            });
                    DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            String seatNo = seatPrefix + seatSuffix;
                            if (!TextUtils.isEmpty(seatNo)) {
                                mUtil.reStoreValueIntoSharePreferences(
                                        CommonUtil.SEATNO, seatNo);
                                mSeatNo = seatNo;
                                // CommandManager.sendSetSeatMessage();
                                Log.d(TAG, "seat no " + mSeatNo);
                                CommandManager.SetSeatNo(seatNo);
                                mHeadBarView.setTitle(mSeatNo);
                                CommandManager.sendSetSeatMessage();
                                handle_saveconf(CommonUtil.getIpPrefix());
                                if (mHandler != null) {
                                    mHandler.removeMessages(MessageHandler.UPDATE_NET_STATUS);
                                    mHandler.sendEmptyMessageDelayed(
                                            MessageHandler.UPDATE_NET_STATUS,
                                            2000);
                                }

                                CommonUtil.configIP(true);
                                CommonUtil.configGATEWAY(11);
                            } else {
                                Toast.makeText(mBaseContext,
                                        "Seat no is null!", Toast.LENGTH_SHORT)
                                        .show();

                            }

                        }
                    };
                    CommonUtil.showCustomDialog(
                            mBaseContext,
                            dialogView,
                            mBaseContext.getResources().getString(
                                    R.string.set_seat), clickListener);

                }
                // TODO ...
                else if (Command.COMMANDS.COMMAND_GLOBAL_HANDSUP.equals(message
                        .getCommand())) {
                    boolean isOn;
                    if ("on".equals(message.getParams())) {
                        isOn = true;
                        // hand_up on
                    } else {
                        isOn = false;
                        // hand_up off
                    }
                    mSwitchManager.notifyHandUpSwitchStatus(isOn, params);

                } else if (Command.COMMANDS.COMMAND_CLEAN.equals(message
                        .getCommand())) {
                    boolean isOn;
                    // CommandManager.leaveGroup();

                }
                return;
            }
        } catch (Exception e) {

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG,"onDestroy");
        unregisterNetworkReceiver();
        unregisterReceiver(mBroadcastReceiver);
        mLibSiren.destroy();
        android.os.Process.killProcess(android.os.Process.myPid());
        mCurrentMOde = null;
        timer.cancel();
    }



    private void killSelfForHeadSet(){
        if(CommonUtil.hasKilled()) {
            if(CommonUtil.getKillTimes() ==0) {
                CommonUtil.setKillTimes(1);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.i(TAG, "kill self");
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }, TIME_THREE_MINUTES);
            }else if(CommonUtil.getKillTimes() ==1) {
                CommonUtil.setKillTimes(0);
                CommonUtil.setHasKilled(false);

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.i(TAG, "kill self");
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }, TIME_ONE_MINUTES);
            }
//            else if(CommonUtil.getKillTimes() ==2) {
//                CommonUtil.setKillTimes(0);
//                CommonUtil.setHasKilled(false);
//                mHandler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        Log.i(TAG, "kill self");
//                        android.os.Process.killProcess(android.os.Process.myPid());
//                    }
//                }, TIME_ONE_MINUTES);
//            }
        }else{


            CommonUtil.setKillTimes(0);
            CommonUtil.setHasKilled(true);
        }

    }

    private class NetworkReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            mNewTime = System.currentTimeMillis();
            if (!mIsInitialized) {
                mHandler.postDelayed(preInvokeNativeTask, 300);
            }
            if (mNewTime - mOldTime >= 3000) {
                Log.d(TAG, "NetworkReceiver connect change1 "
                        + mIsInternetConnected + "===   mIsInitialized ==" + mIsInitialized + " mNewTime - mOldTime "
                        + (mNewTime - mOldTime));
                mOldTime = mNewTime;
                if (!mIsInternetConnected) {
                    if (mHandler != null) {
                        mHandler.removeMessages(MessageHandler.UPDATE_NET_STATUS);
                        mHandler.sendEmptyMessageDelayed(
                                MessageHandler.UPDATE_NET_STATUS, 200);
                    }
                }
            }
        }
    }

    private void registerNetworkReceiver() {
        if (!mNetworkReceiverRegistered) {
            // we only care about the network connect state change
            IntentFilter filter = new IntentFilter(
                    ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(mNetworkReceiver, filter);
            mNetworkReceiverRegistered = true;
        }
    }

    private void unregisterNetworkReceiver() {
        if (mNetworkReceiverRegistered) {

            unregisterReceiver(mNetworkReceiver);
            mNetworkReceiverRegistered = false;
        }
    }

    /**
     * Check the internet state and notify the state.
     *
     * @return true if network available.
     */
    public boolean checkNetworkAvailable() {
        NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();

        if (networkInfo != null) {
            mIsInternetConnected = networkInfo.isConnected();
        } else {
            mIsInternetConnected = false;
        }
        Log.d(TAG, "connect status " + mIsInternetConnected);
        return mIsInternetConnected;
    }

    private void loadWelcomeFragment() {
        if(CommonUtil.APP_THEME_DEFAULT.equals(CommonUtil.getInstance(mBaseContext).getTheme())) {
            mBaseView.setBackgroundResource(R.drawable.bg1);
        }
        FragmentTransaction fragmentTransaction = getFragmentManager()
                .beginTransaction();
        Fragment currentFragment = WelcomeFragment.newInstance(getString(R.string.system_ready));

        fragmentTransaction.replace(R.id.content_container, currentFragment);
        fragmentTransaction.commitAllowingStateLoss();

    }

    private void loadErrorNetworkFragment() {
        FragmentTransaction fragmentTransaction = getFragmentManager()
                .beginTransaction();
        Fragment currentFragment = WelcomeFragment.newInstance(getString(R.string.network_error));

        fragmentTransaction.replace(R.id.content_container, currentFragment);
        fragmentTransaction.commitAllowingStateLoss();

    }

    private void loadFirstFragment() {
        if(CommonUtil.APP_THEME_DEFAULT.equals(CommonUtil.getInstance(mBaseContext).getTheme())) {
            mBaseView.setBackgroundResource(R.drawable.bg1);
        }
        mHeadBarView.setModel(R.string.teach_model);
        MediaMessage firstMessage = new MediaMessage();
        try {
            CommandManager.closeHeadSet();
            Thread.sleep(3000);
            CommandManager.openHeadSet();
        }catch (Exception e){
            e.printStackTrace();
        }
        firstMessage.setCommand(Command.COMMANDS.COMMAND_TEACH_ALLCALLS);
        loadTeachingFragment(firstMessage);
    }

    private void loadTestFragment(){
        if(CommonUtil.APP_THEME_DEFAULT.equals(CommonUtil.getInstance(mBaseContext).getTheme())) {
            mBaseView.setBackgroundResource(R.drawable.sub_bg);
        }
        FragmentTransaction fragmentTransaction = getFragmentManager()
                .beginTransaction();
        Fragment currentFragment = SelfRecordFragment.newInstance(true);

        fragmentTransaction.replace(R.id.content_container, currentFragment);
        fragmentTransaction.commitAllowingStateLoss();
    }

    private void loadTeachingFragment(MediaMessage message) {
        if(CommonUtil.APP_THEME_DEFAULT.equals(CommonUtil.getInstance(mBaseContext).getTheme())) {
            mBaseView.setBackgroundResource(R.drawable.bg1);
        }
        Log.d("command", "loadTeachingFragment +1 " + SystemClock.uptimeMillis());
        if (message.getCommand()
                .equals(Command.COMMANDS.COMMAND_TEACH_ALLCALLS)) {
            TeachDemonstrationFragment.mIsDemonstration = false;
            CommandManager.startSat();
            CommandManager.leaveGroup("");
            CommandManager.joinGroup("230.1.2.3");
            CommandManager.closeMic();
            try {
                CommandManager.closeHeadSet();
                Thread.sleep(3000);
                CommandManager.openHeadSet();
            }catch (Exception e){
                e.printStackTrace();
            }
            Log.d("command", "loadTeachingFragment +2 " + SystemClock.uptimeMillis());
        }
        Log.d("command", "loadTeachingFragment +3 " + SystemClock.uptimeMillis());
        final String params = message.getParams();
        if (message.getCommand().equals(
                Command.COMMANDS.COMMAND_TEACH_DICTATION)) {
            boolean isOn;
            if ("on".equals(params)) {
                isOn = true;
                mSwitchManager.notifyDictationSwitchStatus(isOn, params);
                return;
            } else if ("off".equals(params)) {
                isOn = false;
                mSwitchManager.notifyDictationSwitchStatus(isOn, params);
                return;
            }
        } else if (message.getCommand().equals(
                Command.COMMANDS.COMMAND_TEACH_TRANSLATE)) {
            boolean isOn;
            if ("off".equals(params)) {
                isOn = false;
                mSwitchManager.notifyTranslateSwitchStatus(isOn, params);
                return;
            } else {
                isOn = true;
                mSwitchManager.notifyTranslateSwitchStatus(isOn, params);
                // return;
            }
        } else if (message.getCommand().equals(Command.COMMANDS.COMMAND_TEACH_TEST)) {
            boolean isOn;
            if ("off".equals(params)) {
                isOn = false;
                mSwitchManager.notifyTestSwitchStatus(isOn, params);
                return;
            } else {
                isOn = true;
                mSwitchManager.notifyTestSwitchStatus(isOn, params);
                // return;
            }
        } else if (message.getCommand().equals(
                Command.COMMANDS.COMMAND_TEACH_MULTICAST)) {
            boolean isOn;
            if ("off".equals(params)) {
                isOn = false;
                mSwitchManager.notifyMulticastSwitchStatus(isOn, params);
                return;
            } else if (!"on".equals(message.getParams())) {
                isOn = true;
                mSwitchManager.notifyMulticastSwitchStatus(isOn, params);
                return;
            }
        }

        if (message.getCommand().equals(Command.COMMANDS.COMMAND_CLEAN)) {
            if (message.isMe()) {
                notifyCleanListenner();
            } else if (message.getReveiver().equals("all")) {
                notifyAllCleanListenner();
            }
        }

        FragmentTransaction fragmentTransaction = getFragmentManager()
                .beginTransaction();
        Fragment currentFragment = null;
        if (message.getCommand()
                .equals(Command.COMMANDS.COMMAND_TEACH_ALLCALLS)) {
            try {
                CommandManager.closeHeadSet();
                 Thread.sleep(3000);
                CommandManager.openHeadSet();
            }catch (Exception e){
                e.printStackTrace();
            }
            Log.d("command", "loadTeachingFragment +5 " + SystemClock.uptimeMillis());
            currentFragment = AllCallsFragment.newInstance();
        } else if (message.getCommand().equals(
                Command.COMMANDS.COMMAND_TEACH_DEMONSTRATION)) {
            currentFragment = TeachDemonstrationFragment.newInstance(message);
        } else if (message.getCommand().equals(
                Command.COMMANDS.COMMAND_TEACH_DICTATION)) {
            currentFragment = TeachDictationFragment.newInstance(message);
        } else if (message.getCommand().equals(
                Command.COMMANDS.COMMAND_TEACH_INTERCOM)) {
            currentFragment = TeachIntercomFragment.newInstance(message);
        } else if (message.getCommand().equals(
                Command.COMMANDS.COMMAND_TEACH_MONITOR)) {
            currentFragment = TeachMonitorFragment.newInstance(message);
            // currentFragment = TeachMonitorFragment.newInstance(message);
        } else if (message.getCommand().equals(
                Command.COMMANDS.COMMAND_TEACH_TEST)) {
            currentFragment = TeachTestFragment.newInstance(message);
        } else if (message.getCommand().equals(
                Command.COMMANDS.COMMAND_TEACH_TRANSLATE)) {
            currentFragment = TeachTranslateFragment.newInstance(message);
        } else if (message.getCommand().equals(
                Command.COMMANDS.COMMAND_TEACH_MULTICAST)) {
            currentFragment = TeachBroadcastFragment.newInstance(message);
        } else {
            return;
        }

        fragmentTransaction.replace(R.id.content_container, currentFragment);
        fragmentTransaction.commitAllowingStateLoss();
        Log.d("command", "loadTeachingFragment +6 " + SystemClock.uptimeMillis());
    }

    // load group fragment
    private void loadGroupFragment(MediaMessage message) {
        if(CommonUtil.APP_THEME_DEFAULT.equals(CommonUtil.getInstance(mBaseContext).getTheme())) {
            mBaseView.setBackgroundResource(R.drawable.bg1);
        }
        if (message.getCommand().equals(Command.COMMANDS.COMMAND_GROUP_DISCUSS)) {
            if (!message.isMe()) {
                return;
            }
            Log.d("command", "loadGroupFragment +1 " + SystemClock.uptimeMillis());

            CommandManager.startSat();
            CommandManager.openMic();
            Log.d("command", "loadGroupFragment +2 " + SystemClock.uptimeMillis());
            Log.d("command", "loadGroupFragment +3 " + SystemClock.uptimeMillis());
            Fragment currentFragment = GroupDiscussFragment.newInstance();
            FragmentTransaction fragmentTransaction = getFragmentManager()
                    .beginTransaction();
            fragmentTransaction
                    .replace(R.id.content_container, currentFragment);
            Bundle args = new Bundle();
            args.putSerializable("message", message);
            currentFragment.setArguments(args);
            fragmentTransaction.commitAllowingStateLoss();
            try {
                    CommandManager.closeHeadSet();
                    Thread.sleep(3000);
                    CommandManager.openHeadSet();
                }catch (Exception e){
                    e.printStackTrace();
                }

        }


        if (Command.COMMANDS.COMMAND_GROUP_DISCUSS_RECORD.equals(message
                .getCommand())) {
            boolean isOn;
            final String params = message.getParams();
            if ("off".equals(params)) {
                isOn = false;
                mSwitchManager.notifyDiscussSwitchStatus(isOn, params);
                return;
            } else if ("on".equals(message.getParams())) {
                isOn = true;
                mSwitchManager.notifyDiscussSwitchStatus(isOn, params);
                return;
            }
                    }
        if (message.getCommand().equals(Command.COMMANDS.COMMAND_GROUP_ADJUST)) {
            if (message.isMe()) {
                Log.d(TAG, "join me");
                if (mUpdateGroupMembersListenner != null) {
                    mUpdateGroupMembersListenner.joinMeGroup(message);
                    return;
                }
            } else {
                if (mUpdateGroupMembersListenner != null) {
                    mUpdateGroupMembersListenner.leaveGroup(message
                            .getReveiver());
                    mUpdateGroupMembersListenner.joinGroup(message.getGroup(),
                            message.getReveiver());
                    return;
                }
            }

        }


        if (message.getCommand().equals(
                Command.COMMANDS.COMMAND_GROUP_ATTEND_DISCUSS)) {
            if (message.isMe()) {
                // TODO how show the receiver view;
            } else {
                if (mUpdateGroupMembersListenner != null) {
                    mUpdateGroupMembersListenner.joinGroup(message.getGroup(),
                            message.getReveiver());
                    return;
                }
            }

        }
        if (message.getCommand().equals(
                Command.COMMANDS.COMMAND_GROUP_EXIT_DISCUSS)) {
            if (message.isMe()) {
                // TODO how show the receiver view;
            } else {
                if (mUpdateGroupMembersListenner != null) {
                    mUpdateGroupMembersListenner.leaveGroup(message
                            .getReveiver());
                    return;
                }
            }

        }
    }

    // load exam fragments
    private void loadExamFragment(MediaMessage message) {
        if(CommonUtil.APP_THEME_DEFAULT.equals(CommonUtil.getInstance(mBaseContext).getTheme())) {
            mBaseView.setBackgroundResource(R.drawable.sub_bg);
        }

        final String params = message.getParams();
        if (!mSeatNo.startsWith(message.getReveiver())
                && !message.getReveiver().equals("all")) {
            return;
        }


        Fragment replaceFragment = null;
        FragmentTransaction fragmentTransaction = getFragmentManager()
                .beginTransaction();
        Bundle args = new Bundle();
        args.putString("params", message.getParams());
        args.putString("receiver", message.getReveiver());

        if (Command.COMMANDS.COMMAND_EXAM.equals(message.getCommand())) {
            replaceFragment = ExamReadyFragment.newInstance();
            fragmentTransaction
                    .replace(R.id.content_container, replaceFragment);
        } else if (Command.COMMANDS.COMMAND_EXAM_ORAL.equals(message
                .getCommand())) {
            boolean isOn;
            if ("off".equals(params)) {
                isOn = false;
                mSwitchManager.notifyExamSwitchStatus(isOn, params);
                return;
            } else if ("on".equals(message.getParams())) {
                isOn = true;
                mSwitchManager.notifyExamSwitchStatus(isOn, params);
                return;
            }
            replaceFragment = ExamOralFragment.newInstance(message);
            fragmentTransaction
                    .replace(R.id.content_container, replaceFragment);
        } else if (Command.COMMANDS.COMMAND_EXAM_STANDARD.equals(message
                .getCommand())) {
            boolean isOn;
            if ("off".equals(params)) {
                isOn = false;
                mSwitchManager.notifyExamSwitchStatus(isOn, params);
                return;
            } else if ("on".equals(message.getParams())) {
                isOn = true;
                mSwitchManager.notifyExamSwitchStatus(isOn, params);
                return;
            }
            replaceFragment = ExamStandardFragment.newInstance(message);
            fragmentTransaction
                    .replace(R.id.content_container, replaceFragment);
        } else if (Command.COMMANDS.COMMAND_EXAM_DISCUSS.equals(message
                .getCommand())) {
            boolean isOn;
            if ("off".equals(params)) {
                isOn = false;
                mSwitchManager.notifyExamSwitchStatus(isOn, params);
                return;
            } else {
                isOn = true;
                mSwitchManager.notifyExamSwitchStatus(isOn, params);
            }
            replaceFragment = ExamOralDiscussFragment.newInstance(message);
            replaceFragment.setArguments(args);
            fragmentTransaction
                    .replace(R.id.content_container, replaceFragment);
        }
        if (Command.COMMANDS.COMMAND_EXAM_AUDIO_BROADCAST.equals(message
                .getCommand()) || Command.COMMANDS.COMMAND_GROUP_BROADCAST.equals(message
                .getCommand())) {
            if ("on".equals(params)) {
                mSwitchManager.notifyAudioBroadSwitchStatus(true, params);

                CommandManager.startSat();
                CommandManager.leaveGroup("");
                CommandManager.joinGroup("230.1.2.3");
                CommandManager.closeMic();
                try {
                    CommandManager.closeHeadSet();
                    Thread.sleep(3000);
                    CommandManager.openHeadSet();
                }catch (Exception e){
                    e.printStackTrace();
                }
                Log.i(TAG," joinGroup");
            } else {
                mSwitchManager.notifyAudioBroadSwitchStatus(false, params);
                CommandManager.leaveGroup("");
            }
            Log.d(TAG, "loadExamFragment " + message);
            return;
        }
        if (Command.COMMANDS.COMMAND_EXAM_UPLOAD_FILE_REPEAT.equals(message
                .getCommand())) {
            try {
                if (!TextUtils.isEmpty(params)) {
                    if (params.toUpperCase().contains(mSeatNo.toUpperCase())) {
                        mSwitchManager.notifyUploadFileAgain(true, "upload_file");
                        Log.i(TAG, "upload file again!");
                    }
                }
            }catch (Exception e){
                Log.i(TAG," upload again msg failed !",e);
            }
            return;
        }


        fragmentTransaction.commitAllowingStateLoss();
    }

    // load self study fragments
    private void loadStudyFragment(final MediaMessage message) {
        if(CommonUtil.APP_THEME_DEFAULT.equals(CommonUtil.getInstance(mBaseContext).getTheme())) {
            mBaseView.setBackgroundResource(R.drawable.sub_bg);
        }
        Log.d("command", "loadStudyFragment+1" + SystemClock.uptimeMillis());

        Log.d("jzh", "before destorySat()" + SystemClock.uptimeMillis());
        CommandManager.destorySat();
        Log.d("jzh", "end destorySat()" + SystemClock.uptimeMillis());
        Log.d("command", "loadStudyFragment+2" + SystemClock.uptimeMillis());
        Log.d("command", "loadStudyFragment+3" + SystemClock.uptimeMillis());
        if (Command.COMMANDS.COMMAND_SELF_STUDY.equals(message.getCommand())) {
            {

                Log.d("command", "loadStudyFragment+5" + SystemClock.uptimeMillis());
                Fragment replaceFragment = null;
                FragmentTransaction fragmentTransaction = getFragmentManager()
                        .beginTransaction();
                replaceFragment = SelfStudyFragment.newInstance(message);
                Bundle args = new Bundle();
                args.putSerializable("message", message);
                fragmentTransaction.replace(R.id.content_container,
                        replaceFragment);
                fragmentTransaction.commitAllowingStateLoss();
            }

        }else if (Command.COMMANDS.COMMAND_GLOBAL_MACHINE_TEST.equals(message.getCommand())){
            loadTestFragment();
        }


        Log.d("command", "loadStudyFragment+3" + SystemClock.uptimeMillis());
        if (Command.COMMANDS.COMMAND_SELF_IP_CALL.equals(message.getCommand())) {
            if (message.getReveiver().equals(mSeatNo)) {
                new AlertDialog.Builder(this)
                        .setTitle("Ip Call")
                        .setMessage("Call from " + message.getParams())
                        .setPositiveButton("receive",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface arg0,
                                                        int arg1) {
                                        CommandManager.joinGroup(GroupInfo
                                                .getGroupId(message.getGroup()));

                                    }
                                }).setNegativeButton("cancel", null).create()
                        .show();
            }
        }

        if (Command.COMMANDS.COMMAND_SELF_REFRESH.equals(message.getCommand())) {
            if (mUpdateResources != null) {
                mUpdateResources.updateUrl(message.getParams());
            }
        }
    }

    private IUpdateGroupMembersListenner mUpdateGroupMembersListenner;

    public void registerUpdateGroupMembersListenner(
            IUpdateGroupMembersListenner l) {
        mUpdateGroupMembersListenner = l;
    }

    public void unregisterUpdateGroupMembersListenner() {
        mUpdateGroupMembersListenner = null;
    }

    public void registerCleanListener(ICleanListener l) {
        mCleanerList.add(l);
    }

    public void unregisterCleanListener(ICleanListener l) {
        mCleanerList.remove(l);
    }

    public void notifyCleanListenner() {
        for (int i = 0; i < mCleanerList.size(); i++) {
            mCleanerList.get(i).clean();
        }
    }

    public void notifyAllCleanListenner() {
        for (int i = 0; i < mCleanerList.size(); i++) {
            mCleanerList.get(i).allClean();
        }
    }

    private IUpdateResources mUpdateResources;

    public interface IUpdateResources {
        public void updateUrl(String url);
    }

    public void setUpdateResources(IUpdateResources updateResources) {
        mUpdateResources = updateResources;
    }

    private void handle_saveconf(String mIpPrefix) {
        EthernetManager mEthManager = EthernetManager.getInstance();
        mEthManager.setEnabled(true);
        EthernetDevInfo mEthInfo = mEthManager.getSavedConfig();
        Log.d("mmclass", "handle_saveconf" + "IP :" + mEthInfo.getIpAddress()
                + " " + mEthInfo.getConnectMode());
        Log.d("ethernet info", "IP :" + mEthInfo.getIpAddress() + " "
                + mEthInfo.getConnectMode());
        EthernetDevInfo info = new EthernetDevInfo();
        info.setIfName(mEthInfo.getIfName());

        info.setConnectMode(EthernetDevInfo.ETHERNET_CONN_MODE_MANUAL);
        info.setIpAddress(mIpPrefix + "." + GroupInfo.sAddressMap.get(mSeatNo));
        info.setGateWay(mIpPrefix + ".11");
        info.setDnsAddr(mIpPrefix + ".11");
        info.setNetMask("255.255.255.0");
        mEthManager.updateDevInfo(info);
    }

    @Override
    public void onBackPressed() {
    }

    private void initDownload() {
        mThread.start();
        mDownloadHandler = new Handler(mThread.getLooper());
        mSession = new Session();
        mSession.setContext(this);
    }

    /*
     * Download the file.
     *
     * @param dest
     *
     * @throws RemoteException
     */
    public void download(String url) throws RemoteException {
        Log.d(TAG, "SystemUpdateServiceStub.download");
        // mSession.setRunInBackgroud(false);
        // Tiger - hard code /cache as the first try. 2013.12.31
        mSession.setDownloadTo("/cache/update/", Constants.UPGRADE_FILE_BODY);
        mSession.setNewVersionURL(url);
        Log.d(TAG, "download start");
        m_pDialog.show();
        IDownloadListener l = new IDownloadListener() {

            @Override
            public boolean onChangeDownloadPath(Session session) {
                Log.e("Download", "this should not be called\n");
                return false;

            }

            @Override
            public void onCompleted(Session session) {
                Log.e("Download", "onCompleted()");
                mSession.setState(Constants.STATE_REBOOTING);
                Log.e("Download", "reboot and upgrade!");
                // RebootTask task = new RebootTask(mSession);
                // mDownloadHandler.post(task);
                sIsDownloaded = true;
                RebootTask task = new RebootTask(mSession);
                mDownloadHandler.post(task);

            }

            @Override
            public void onError(Session session, int errorCode) {
                Log.e("Download", "onError()");
            }

            @Override
            public void onDownloading(Session session) {
                Message msg = mHandler.obtainMessage(MessageHandler.UPDAGE_DOWNLOADING);
                msg.arg1 = (int) session.getDownlaodedFileSize();
                msg.arg2 = (int) session.getNewVersionFileSize();
                mHandler.sendMessage(msg);
                Log.d(TAG, "download info " + msg.arg1 + "  " + msg.arg2);
            }
        };
        mDownloadTask = new DownloadTask(mSession, l);
        mDownloadHandler.post(mDownloadTask);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int keyCode = event.getKeyCode();
        final int action = event.getAction();
        Log.d(TAG, "keycode :" + event.getKeyCode());
        Log.i("keyevent", "dispatchKeyEvent keyCode" + keyCode + " isShiftPressed " + event.isShiftPressed());
        if (keyCode == KeyEvent.KEYCODE_F6 || keyCode == KeyEvent.KEYCODE_F5 || keyCode == KeyEvent.KEYCODE_F7 ||keyCode == KeyEvent.KEYCODE_F9|| keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_SHIFT_LEFT) {
            return mHeadBarView.dispatchKeyEvent(event);
        } else if(keyCode == KeyEvent.KEYCODE_F10){
            if (action == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                showRebootDialog();
            }
            return true;
        }else{
            return super.dispatchKeyEvent(event);
        }
    }

    public void turnOnScreen() {
        // turn on
        boolean isScreenOn = mPowerManager.isScreenOn();
        if (!isScreenOn) {
            mPowerManager.wakeUp(SystemClock.uptimeMillis());
        }
        Log.d(TAG, "isScreenOn turnOnScreen " + isScreenOn);
    }

    public void turnOffScreen() {
        boolean isScreenOn = mPowerManager.isScreenOn();
        if (mPowerManager.isScreenOn()) {
            mPowerManager.goToSleep(SystemClock.uptimeMillis());
        }
        Log.d(TAG, "isScreenOn turnOffScreen " + isScreenOn);
    }

    public void checkEth0DeviceAndSetStatus() {
        int flag = CommandManager.getLocalEth0Info();
        if (flag == 0) {
            Log.d(TAG, "eth0 doesn't found change gpio");
            CommonUtil.resetEthoGpio(0);
            try {
                Thread.sleep(1000);

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            CommonUtil.resetEthoGpio(1);
        } else if (flag == 1) {
            Log.d(TAG, "eth0 found");
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

    }

    private void killOtherProcess() {
        try {
            mSwitchManager.notifyKillPlayerSwitchStatus(true, null);
//            KillProcessUtils.getInstance().killProcess(mBaseContext);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showRocektShot() {
        WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
        WindowManager mWindowManager = (WindowManager) getApplication().getSystemService(getApplication().WINDOW_SERVICE);
        wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        wmParams.format = PixelFormat.RGBA_8888;
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        wmParams.gravity = Gravity.RIGHT | Gravity.TOP;
        wmParams.x = 0;
        wmParams.y = 0;
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        LayoutInflater inflater = LayoutInflater.from(getApplication());
        mRocketView = (LinearLayout) inflater.inflate(R.layout.rocket_shot, null);
        mWindowManager.addView(mRocketView, wmParams);
        launcherTheRocket();
    }

    private void launcherTheRocket() {
        mHandler.postDelayed(new Runnable() {

            @Override
            public void run() {
                final View rocket = mRocketView.findViewById(R.id.rocket);
                //初始化
                Animation rocketAnimation = AnimationUtils.loadAnimation(
                        getApplicationContext(), R.anim.rocket);
                //设置动画监听
                rocketAnimation
                        .setAnimationListener(new VisibilityAnimationListener(
                                rocket));
                //开启
                rocket.startAnimation(rocketAnimation);

                final View cloud = mRocketView.findViewById(R.id.cloud);
                Animation cloudAnimation = AnimationUtils.loadAnimation(
                        getApplicationContext(), R.anim.cloud);
                cloudAnimation
                        .setAnimationListener(new VisibilityAnimationListener(
                                cloud));
                cloud.startAnimation(cloudAnimation);

                final View launcher = mRocketView.findViewById(R.id.launcher);
                Animation launcherAnimation = AnimationUtils.loadAnimation(
                        getApplicationContext(), R.anim.launcher);
                launcherAnimation
                        .setAnimationListener(new VisibilityAnimationListener(launcher));
                launcher.startAnimation(launcherAnimation);

            }
        }, 150);

    }

    static class VisibilityAnimationListener implements Animation.AnimationListener {

        private View mVisibilityView;

        public VisibilityAnimationListener(View view) {
            mVisibilityView = view;
        }

        public void setVisibilityView(View view) {
            mVisibilityView = view;
        }

        //动画开始
        @Override
        public void onAnimationStart(Animation animation) {
            Log.i("START", "...");
            if (mVisibilityView != null) {
                mVisibilityView.setVisibility(View.VISIBLE);
                // mVisibilityView.setVisibility(View.GONE);
            }

        }

        //动画结束
        @Override
        public void onAnimationEnd(Animation animation) {
            Log.i("END", "...");
            if (mVisibilityView != null) {
                mVisibilityView.setVisibility(View.GONE);
            }
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }
    }

   public static interface VolumeChangeListener {
        public void volumeChanger(String msg);
    }

    VolumeChangeListener mVolumeChangeListener;

    public void setVolumeChangeListener(VolumeChangeListener changeListener) {
        this.mVolumeChangeListener = changeListener;
    }

    class MyTask extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... arg0) {
            String url = arg0[0];
            if (TextUtils.isEmpty(url)) {
                return "";
            }
            String result = CommonUtil.getDataFromUrl(url);
            return result;
        }

        protected void onPostExecute(String result) {
            if (TextUtils.isEmpty(result)) {
                mHandler.removeMessages(MessageHandler.PING_ERROR);
                mHandler.sendEmptyMessage(MessageHandler.PING_ERROR);
                return;
            }
            if (!TextUtils.isEmpty(result)) {
                Log.d(TAG, result);
                try {
                    JSONObject jb  = new JSONObject(result);
                    int status = jb.getInt("Status");
                    //!99 代表教师端已经上线
                    if(status!=99){
                        //发送online命令检查 命令通道是否畅通 5s后检查是否返回ok指令
                        sIsAlive = true;

//                        CommandManager.sendSetOnlineMessage();

                    }else{
                        //99 代表教师端没有上线 此时不做处理
                        Log.i(TAG,"教师端不在线,无须处理");
                        sIsAlive = false;
                    }
                } catch (Exception e) {
                    Log.e(TAG, "error" + e.toString());
                    sIsAlive = false;
                }

                mHandler.removeMessages(MessageHandler.CHECK_ALIVE);
                mHandler.sendEmptyMessageDelayed(MessageHandler.CHECK_ALIVE,10*1000);
            }
        }

    }

    private void checkTeachServer(){
        Log.i(TAG,"checkTeachServer");
        new MyTask().execute(sCheckUrl+mSeatNo);
    }

    private  void showDialog(){
        DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
//                android.os.Process.killProcess(android.os.Process.myPid());
            }
        };
        if(sAlertDialog==null) {
            sAlertDialog = CommonUtil.showWarnDialog(BaseActivity.this, "网络异常", "连接不到服器器，请重启！", clickListener,null);
        }
        if(!sAlertDialog.isShowing()){
            sAlertDialog.show();
        }
    }
    private void dimissDialog(){
        if(sAlertDialog!=null){
            sAlertDialog.dismiss();
        }
    }


    private  void showRebootDialog(){
       // mIsNeedAutoReboot = true;
       // mHandler.removeMessages(MessageHandler.REBOOT);
       // mHandler.sendEmptyMessageDelayed(MessageHandler.REBOOT,10*1000);
        DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                PowerManager pManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
                pManager.reboot("reboot");
            }
        };

        DialogInterface.OnClickListener cancelListenser = new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
               // mHandler.removeMessages(MessageHandler.REBOOT);
                //mIsNeedAutoReboot = false;
            }
        };

        AlertDialog  dialog= CommonUtil.showWarnDialog(BaseActivity.this, "重启机器", "是否重启机器！", clickListener,cancelListenser);
        dialog.show();

    }
    private boolean mIsNeedAutoReboot = false;
}
